let mysql = require('mysql');
let fs = require('fs');
let db = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'information_schema',
    multipleStatements: true
});
let newdb = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'newapi',
    multipleStatements: true
});
db.connect(function(err) {
    if (err) {
        return;
    }
});
newdb.connect(function(err) {
    if (err) {
        return;
    }
});
var newstr = [];
function titleCase(str) {
    newstr = [];
    str = str.toLowerCase().split("_");
    for (var i = 0; i < str.length; i++) {
        var char = str[i].charAt(0);
        str[i] = str[i].replace(char, function(s) {
            return s.toUpperCase();
        });
    }
    var i = 0;
    let tt = "";
    str.forEach(info => {
        if (i > 0) {
            tt += info
        }
        i++;
    });
    newstr.push(tt.split("\n")[0]);
}
let $exp = [];
let $phpName = '';  
let $ControllerName = '';
let $comment = '';   
let $buildsql = ''; 
let $frontApi = ''; 
let $frontVue = ''; 
let $backModel = '';
let $backController = ''; 
let $formItem = "";
let $columnsList = "";
let $formitem = "";
let $editformitem = "";
let $fid = 0;
let $parentsName = 'NewApi';
let $parentssql = "INSERT	INTO admin_menu VALUES(0,'" + $parentsName + "',0,'',0,0,0,'',0);";
let $fidsql = "select id from admin_menu where name='" + $parentsName + "'  order by id desc ;";
let tables = function() {
    return new Promise(function(resolve, reject) {
        db.query("SELECT * From TABLES where TABLE_SCHEMA='NewApi' AND TABLE_NAME like '%db_%' and TABLE_NAME !='migrations'  ORDER BY CONVERT( TABLE_COMMENT USING gbk ) COLLATE gbk_chinese_ci  ASC", function(err, rows, fields) {
            resolve(rows)
        })
    }).catch(function(err) {
        reject(err)
    })
};
let columns = function(sql) {
    return new Promise(function(resolve, reject) {
        db.query(sql, function(err, rows, fields) {
            resolve(rows)
        })
    }).catch(function(err) {
        reject(err)
    });
};
let asyncWriteFile = function(path, code) {
    return new Promise(function(resolve, reject) {
        fs.writeFile("code/" + path, code, {},
            function(err) {
                if (err) {
                    console.log(err);
                }
            })
    }).catch(function(err) {
        reject(err)
    });
};
newdb.query($parentssql, function(err, rows, fields) {
    newdb.query($fidsql, function(err, rows, fields) {
        $fid = rows[0]["id"];
        tables().then(tables => {
            tables.forEach(table => {
                titleCase(table.TABLE_NAME);
                $exp = newstr;
                newstr = [];
                $phpName = 'Db' + $exp;
                $ControllerName = $exp;
                $comment = table.TABLE_COMMENT;
                $buildsql = `INSERT	INTO admin_menu VALUES(0,'${$comment}查询',${$fid},'admin/${$ControllerName}/index',0,0,0,'',0);
              INSERT	INTO admin_menu VALUES(0,'${$comment}新增',${$fid},'admin/${$ControllerName}/add',0,0,0,'',0);
              INSERT	INTO admin_menu VALUES(0,'${$comment}编辑',${$fid},'admin/${$ControllerName}/edit',0,0,0,'',0);
              INSERT	INTO admin_menu VALUES(0,'${$comment}删除',${$fid},'admin/${$ControllerName}/del',0,0,0,'',0);
              INSERT	INTO admin_auth_rule VALUES(0,'admin/${$ControllerName}/index',1,0,1);
              INSERT	INTO admin_auth_rule VALUES(0,'admin/${$ControllerName}/add',1,0,1);
              INSERT	INTO admin_auth_rule VALUES(0,'admin/${$ControllerName}/edit',1,0,1);
              INSERT	INTO admin_auth_rule VALUES(0,'admin/${$ControllerName}/del',1,0,1);`;
                newdb.query($buildsql, function(err, rows, fields) {
                })
            })
        })
    })
});

tables().then(tables => {
    tables.forEach(table => {
        titleCase(table.TABLE_NAME);
        $exp = newstr;
        newstr = [];
        $exp.forEach(exp => {
            $phpName = 'Db' + exp;
            $ControllerName = exp;
            $comment = table.TABLE_COMMENT;
            $backController = `<?php
            namespace app\\admin\\controller;
            use app\\model\\${$phpName};
            use app\\util\\ReturnCode;
            use app\\util\\Tools;
            class ${$ControllerName} extends Base
            {
                public function index()
                {
                    $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
                    $start = $this->request->get('page', 1);
                    $keywords = $this->request->get('keywords', '');
                    $obj = new ${$phpName}();
                    // $obj = $obj->whereLike('', '%%');
                    $listObj = $obj->order('id')->paginate($limit, false, ['page' => $start])->toArray();
                    return $this->buildSuccess([
                        'list'  => $listObj['data'],
                        'count' => $listObj['total']
                    ]);
                }
                public function add()
                {
                    $postData = $this->request->post();
                    $res = ${$phpName}::create($postData);
                    if ($res === false) {
                        return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败！');
                    } else {
                        return $this->buildSuccess([]);
                    }
                }
                public function edit()
                {
                    $postData = $this->request->post();
                    $res = ${$phpName}::update($postData);
                    if ($res === false) {
                        return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败！');
                    } else {
                        return $this->buildSuccess([]);
                    }
                }
                public function del()
                {
                    $id = $this->request->get('id');
                    if (!$id) {
                        return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数！');
                    } else {
                        ${$phpName}::destroy($id);
                        return $this->buildSuccess([]);
                    }
                }
            }`;
            asyncWriteFile($ControllerName + '.php', $backController).then(res => {
                $backController = ``;
            });
            $backModel = `<?php
                    namespace app\\model;
                    class ${$phpName} extends Base {}`;
            asyncWriteFile($phpName + '.php', $backModel).then(res => {
            });
        });
        let formItem = "";
        let columnsList = "";
        let editformitem = "";
        let formitem = "";
        let itemName = "";

        let keywordsName = ""; 
        let keywords = "";
        titleCase(table.TABLE_NAME);
        let $exp2 = newstr;
        columns("SELECT * From COLUMNS where TABLE_SCHEMA='newapi' AND TABLE_NAME ='" + table.TABLE_NAME + "'").then(item => {
            item.forEach(info => {
                if (info.COLUMN_NAME != 'id' && info.COLUMN_NAME != 'sort' && info.COLUMN_NAME != 'sort' && info.COLUMN_NAME != 'create_time' && info.COLUMN_NAME != 'update_time' && info.COLUMN_NAME != 'status') {
                    formItem += `${info.COLUMN_NAME}:'',`;
                    columnsList += `{
                            title: '${info.COLUMN_COMMENT}',
                            align: 'center',
                            key:'${info.COLUMN_NAME}',
                            width: 'auto'
                          },`;
                    editformitem += `vm.formItem.${info.COLUMN_NAME} = currentRow.${info.COLUMN_NAME};`;
                    formitem += ` 
                        <FormItem label='${info.COLUMN_COMMENT}' prop='${info.COLUMN_NAME}'>
                         <Input v-model='formItem.${info.COLUMN_NAME}' placeholder='请输入${info.COLUMN_COMMENT}'></Input>
                       </FormItem>`;
                    itemName += `${info.COLUMN_COMMENT},`;
                }
            });
            $formItem = formItem;
            $columnsList = columnsList;
            $editformitem = editformitem;
            $formitem = formitem;

            $phpName = $exp2[0];
            $phpName += $exp2[1];
            $ControllerName = $exp2[0];
            keywords = $formItem.split(',')[0].split(':')[0];
            keywordsName = itemName.split(',')[0];

            $frontApi = `
            import axios from '@/libs/api.request'
            export const getList = (params) => {
              return axios.request({
                url: '${$ControllerName}/index',
                method: 'get',
                params: params
              })
            }
            export const add = (data) => {
              return axios.request({
                url: '${$ControllerName}/add',
                method: 'post',
                data
              })
            }
            export const edit = (data) => {
              return axios.request({
                url: '${$ControllerName}/edit',
                method: 'post',
                data
              })
            }
            export const del = (id) => {
              return axios.request({
                url: '${$ControllerName}/del',
                method: 'get',
                params: {
                  id: id
                }
              })
            }`;
            asyncWriteFile($ControllerName + '.js', $frontApi).then(res => {
                $frontApi = ``;
            });
            $frontVue = ` <style lang='less' scoped>
            </style>
            <template>
              <div>
                <Row>
                  <Col span='24'>
                    <Card style='margin-bottom: 10px'>
                      <Form inline>
                        <FormItem style='margin-bottom: 0'>
                          <Input v-model='searchConf.keywords' placeholder></Input>
                        </FormItem>
                        <FormItem style='margin-bottom: 0'>
                          <Button
                            type='primary'
                            @click='search'
                          >{{ $t('find_button') }}/{{ $t('refresh_button') }}</Button>
                        </FormItem>
                      </Form>
                    </Card>
                  </Col>
                </Row>
                <Row>
                  <Col span='24'>
                    <Card>
                      <p slot='title' style='height: 32px'>
                        <Button type='primary' @click='alertAdd' icon='md-add'>{{ $t('add_button') }}</Button>
                      </p>
                      <div>
                        <Table :columns='columnsList' :data='tableData' border disabled-hover></Table>
                      </div>
                      <div class='margin-top-15' style='text-align: center'>
                        <Page
                          :total='tableShow.listCount'
                          :current='tableShow.currentPage'
                          :page-size='tableShow.pageSize'
                          @on-change='changePage'
                          @on-page-size-change='changeSize'
                          show-elevator
                          show-sizer
                          show-total
                        ></Page>
                      </div>
                    </Card>
                  </Col>
                </Row>
                <Modal
                  v-model='modalSetting.show'
                  width='668'
                  @on-visible-change='doCancel'>
                  <p slot='header' style='color:#2d8cf0'>
                    <Icon type='md-alert'></Icon>
                    <span>{{formItem.id ? '编辑' : '新增'}}</span>
                  </p>
                  <Form ref='myForm' :rules='ruleValidate' :model='formItem' :label-width='100'>
                   ${$formitem}
                  </Form>
                  <div slot='footer'>
                   <Button type='text' @click='cancel' style='margin-right: 8px'>取消</Button>
                   <Button type='primary' @click='submit' :loading='modalSetting.loading'>确定</Button>
                  </div>
                </Modal>
              </div>
            </template>
            <script>
            import { getList, del, add, edit, changeStatus } from '@/api/business/${$ControllerName}';
            import { getDate } from '@/libs/tools';
            const editButton = (vm, h, currentRow, index) => {
              return h(
                'Button',
                {
                  props: {
                    type: 'primary'
                  },
                  style: {
                    margin: '0 5px'
                  },
                  on: {
                    click: () => {
                      vm.formItem.id = currentRow.id;
                      ${$editformitem}
                      vm.formItem.sort = currentRow.sort;
                      vm.modalSetting.show = true;
                      vm.modalSetting.index = index;
                    }
                  }
                },
                vm.$t('edit_button')
              );
            };
            const deleteButton = (vm, h, currentRow, index) => {
              return h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除这条数据吗? ',
                    transfer: true
                  },
                  on: {
                    'on-ok': () => {
                      del(currentRow.id).then(response => {
                        vm.tableData.splice(index, 1);
                        vm.$Message.success(response.data.msg);
                      });
                      currentRow.loading = false;
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        margin: '0 5px'
                      },
                      props: {
                        type: 'error',
                        placement: 'top',
                        loading: currentRow.isDeleting
                      }
                    },
                    vm.$t('delete_button')
                  )
                ]
              );
            };
            export default {
              name: 'shop',
              data() {
                return {
                  columnsList: [
                    ${$columnsList}
                    {
                        title: '修改时间',
                        align: 'center',
                        render: (h, params) => {
                          return h('span', params.row.update_time);
                        },
                        width: 200
                      },
                      {
                        title: '创建时间',
                        align: 'center',
                        render: (h, params) => {
                          return h('span', params.row.create_time);
                        },
                        width: 200
                      },
                      {
                        title: '操作',
                        align: 'center',
                        width: 200,
                        render: (h, params) => {
                          return h('div', [
                            editButton(this, h, params.row, params.index),
                            deleteButton(this, h, params.row, params.index)
                          ]);
                        }
                      }
                  ],
                  tableData: [],
                  groupList: [],
                  tableShow: {
                    currentPage: 1,
                    pageSize: 10,
                    listCount: 0
                  },
                  searchConf: {
                    type: '',
                    keywords: '',
                    status: ''
                  },
                  modalSetting: {
                    show: false,
                    loading: false,
                    index: 0
                  },
                  formItem: {
                    id:0,
                    ${$formItem}
                  },
                  ruleValidate: {
                    ${keywords}: [
                        { required: true, message: '${keywordsName}不能为空', trigger: 'blur' }
                    ]
                  }
                };
              },
              created() {
                this.getList();
              },
              methods: {
                alertAdd() {
                  let vm = this;
                  this.modalSetting.show = true;
                },
                submit() {
                  let vm = this;
                  this.$refs['myForm'].validate(valid => {
                    if (valid) {
                      vm.modalSetting.loading = true;
                      if (vm.formItem.id === 0) {
                        add(vm.formItem)
                          .then(response => {
                            vm.$Message.success(response.data.msg);
                            vm.getList();
                            vm.cancel();
                          })
                          .catch(() => {
                            vm.cancel();
                          });
                      } else {
                        edit(vm.formItem)
                          .then(response => {
                            vm.$Message.success(response.data.msg);
                            vm.getList();
                            vm.cancel();
                          })
                          .catch(() => {
                            vm.cancel();
                          });
                      }
                    }
                  });
                },
                cancel() {
                  this.modalSetting.show = false;
                },
                doCancel(data) {
                  if (!data) {
                    this.formItem.id = 0;
                    this.$refs['myForm'].resetFields();
                    this.modalSetting.loading = false;
                    this.modalSetting.index = 0;
                  }
                },
                changePage(page) {
                  this.tableShow.currentPage = page;
                  this.getList();
                },
                changeSize(size) {
                  this.tableShow.pageSize = size;
                  this.getList();
                },
                search() {
                  this.tableShow.currentPage = 1;
                  this.getList();
                },
                getList() {
                  let vm = this;
                  let params = {
                    page: vm.tableShow.currentPage,
                    size: vm.tableShow.pageSize,
                    keywords: vm.searchConf.keywords
                  };
                  getList(params).then(response => {
                    vm.tableData = response.data.data.list;
                    vm.tableShow.listCount = response.data.data.count;
                  });
                }
              }
            };
            </script>`;
            asyncWriteFile($ControllerName + '.vue', $frontVue).then(res => {
                $frontVue = ``;
            });
        })
    })
})